package com.nobody.facepk.persist.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;


public class ConfigType implements org.hibernate.usertype.UserType{
	public int[] sqlTypes() {
		return new int[]{Types.CHAR};
	}

	public Class returnedClass() {
		return Config.class;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return ( x == y ) || ( x != null && x.equals( y ) );
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		Config config = new Config();
		String value = rs.getString(names[0]);
		String[] tokens = value.split("\\|");
		for(String token : tokens) {
			if(token==null || StringUtils.isEmpty(token)) {
				String[] pair = token.split("\\=");
				if(pair.length>1) {
					config.setValue(pair[0], pair[1]);
				}
			}
		}
		return config;
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if ( value != null ) {
			StringBuilder buffer = new StringBuilder();
			Config config = (Config) value;
			for(String key : config.getConfigMap().keySet()) {
				buffer.append(key).append("=").append(config.getString(key)).append("|");
			}
			st.setString(index,buffer.toString());
		}
		else {
			st.setNull( index, sqlTypes()[0] );
		}
	}

	public Object deepCopy(Object value) throws HibernateException {
		Config config = (Config)value;
		Config newConfig = new Config();
		for(String key : config.getConfigMap().keySet()) {
			newConfig.setValue(key, config.getString(key));
		}
		return newConfig;
	}

	public boolean isMutable() {
		return false;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}
}
